package ru.smc.hogwarts.servlets.messages;

import java.io.IOException;
import java.util.Date;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import ru.smc.hogwarts.classes.EMF;
import ru.smc.hogwarts.model.Message;
import ru.smc.hogwarts.model.Person;

public class MessagesNew extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private HttpSession session;
	private String error = "";
	private String body = null;
	private String subject = null;
	private int id;
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setAttribute("error", error);
		EntityManagerFactory emf = EMF.getInstance().getEMF();
   	    EntityManager em = emf.createEntityManager();
		session = request.getSession(true);
		//int id = 0;
		Object sender= null;
		session.setAttribute("servletName", getServletName());
		if (error == "") {
			body = null;
			subject = null;
		}
		request.setAttribute("body", body);
		request.setAttribute("subject", subject);
		
		try {
			id = Integer.parseInt(request.getParameter("id"));
		} catch (NumberFormatException e) {}
		
//		if (pid==0){
//			Query query = em.createQuery("select p from People p where p.id=?1");
//			id = (Integer)session.getAttribute("userID");
//			query.setParameter(1, id);
//	    	try{
//	       		sender = query.getSingleResult();
//	        	}
//	    	catch (NoResultException er) {
//	//    		request.getRequestDispatcher("messages/messagesList.jsp").forward(request, response);
//	    	}
//	    	request.setAttribute("sender", sender);
//		}
		
		if (id!=0){
			sender=em.find(Person.class, id);
			request.setAttribute("sender", sender);
		}
		em.close();
		request.getRequestDispatcher("/pages/messages/messageNew.jsp").forward(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		error = "";
		int id = 0;
		session = request.getSession(true);
		try {
			try {
				id = Integer.parseInt(request.getParameter("id"));
			} catch(NumberFormatException e) {}
			
			body = request.getParameter("body");
			if (body == "") error += "<span>П</span>оле \"Сообщение\" не должно быть пустым.<br>";
			subject = request.getParameter("subject");
			if (subject == "") error += "<span>П</span>оле \"Тема\" не должно быть пустым.<br>";
		} 
		catch(Exception e) {
			e.printStackTrace();
		}
		if (error == "") { 
			EntityManagerFactory emf = EMF.getInstance().getEMF();
	    	EntityManager em = emf.createEntityManager();
			em.getTransaction().begin();
			Message message = new Message();
			message.setBody(body);
			message.setSubject(subject);
			message.setReaded(false);
			Person person = new Person();
			person = em.find(Person.class, id);
			message.setRecipient(person);
			person = em.find(Person.class, (Integer)session.getAttribute("userID"));
			message.setSender(person);
			java.util.Date utilDate = new Date();
			java.sql.Date date = new java.sql.Date(utilDate.getTime());
			message.setCreated(date);
			message.setDeletetedr(false);
			message.setDeleteteds(false);
			em.persist(message);
			em.getTransaction().commit();
			em.close();
			response.sendRedirect(request.getContextPath() + "/messages");
		} else if (error != "") {
			response.sendRedirect(request.getContextPath() + "/messages/new?id="+id);
		}
	}

}
